package fun.easycode.webterminal.common.config;

import cn.hutool.json.JSONUtil;
import jakarta.servlet.http.HttpServletRequest;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.http.HttpMethod;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

/**
 * 日志打印
 * @author xuzhen
 */
@Aspect
@Slf4j
@Component
public class ApiLogAop {

    @Pointcut("execution(* fun.easycode.webterminal.adapter.api..*.*(..))")
    public void pointCut() { }


    @Around("pointCut()")
    public Object doApiLogAround(ProceedingJoinPoint joinPoint) throws Throwable {

        long start = System.currentTimeMillis();
        Object result = joinPoint.proceed();
        // 请求时间
        long useTime = System.currentTimeMillis() - start;

        if(RequestContextHolder.getRequestAttributes() == null){
            return result;
        }

        HttpServletRequest request = ((ServletRequestAttributes)RequestContextHolder.getRequestAttributes()).getRequest();
        // 请求URL
        String url = request.getRequestURL().toString();
        // 请求方式
        String method = request.getMethod();
        // 请求参数
        String param = getaParam(joinPoint, method, request);;

        // GET请求暂时不打印响应内容，没啥用
        if ("GET".equals(method)) {
            log.info("请求地址：{}, 请求内容：{}, 请求方式：{}, 响应时间：{}ms.",
                    url, param, method, useTime );
        } else {
            log.info("请求地址：{}, 请求内容：{}, 请求方式：{}, 响应时间：{}ms, 响应内容：{}",
                    url, param, method, useTime, JSONUtil.toJsonStr(result));
        }
        return result;
    }

    /**
     * 获取请求参数
     */
    public String getaParam(JoinPoint joinPoint, String method, HttpServletRequest request) {
        if (HttpMethod.GET.toString().equals(method)) {
            return request.getQueryString();
        } else {
            Object[] paramsArray = joinPoint.getArgs();
            return JSONUtil.toJsonStr(paramsArray);
        }
    }

}